package com.assist.converters;

import java.util.ArrayList;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import javax.faces.convert.FacesConverter;

import com.assist.model.Category;
import com.assist.service.ICategoryService;
import com.assist.service.impl.CategoryServiceImpl;

@FacesConverter("categoryConverter")
public class CategoryConverter implements Converter{

	public static List<Category> categories;
	private static ICategoryService categoryService;
	
    static {
    	categories = new ArrayList<Category>();
    	
		categoryService = new CategoryServiceImpl();		
		categories = categoryService.getCategories();

    }

    public Object getAsObject(FacesContext facesContext, UIComponent component, String submittedValue) {
        if (submittedValue.trim().equals("")) {
            return null;
        } else {
            try {
                int id = Integer.parseInt(submittedValue);

                for (Category c : categories) {
                    if (c.getId() == id) {
                        return c;
                    }
                }
                
            } catch(NumberFormatException exception) {
                throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Conversion Error", "Not a valid category"));
            }
        }

        return null;
    }

    public String getAsString(FacesContext facesContext, UIComponent component, Object value) {
        if (value == null || value.equals("")) {
            return "";
        } else {
            return String.valueOf(((Category) value).getId());
        }
    }

}
